<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>健康管理系统</h2>
        <p>欢迎登录</p>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="studentNumber">
          <el-input v-model="loginForm.studentNumber" placeholder="请输入学号/工号">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div class="remember-forgot">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-link type="primary" @click="goToForgetPassword">忘记密码?</el-link>
        </div>
        <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">
          登录
        </el-button>
        <div class="register-link">
          <span>还没有账号?</span>
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </div>
    <div class="project-info">西南科技大学智慧教育研究中心项目及项目编号</div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance | null>(null)
const loading = ref(false)

const loginForm = reactive({
  studentNumber: '',
  password: '',
  remember: false,
})

// 如果localStorage中有存储的学号，自动填充
onMounted(() => {
  const savedStudentNumber = localStorage.getItem('studentNumber')
  if (savedStudentNumber) {
    loginForm.studentNumber = savedStudentNumber
    loginForm.remember = true
  }
})

const loginRules = {
  studentNumber: [{ required: true, message: '请输入学号/工号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

const handleLogin = async () => {
  try {
    await loginFormRef.value?.validate()

    loading.value = true
    // 构造登录请求数据
    const loginData = {
      studentNumber: loginForm.studentNumber,
      password: loginForm.password,
    }

    try {
      // 使用fetch API直接发送请求
      const response = await fetch('/api/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginData),
        credentials: 'include', // 包含cookies
      })

      console.log('登录响应状态:', response.status)

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const res = await response.json()
      console.log('登录响应数据:', res)

      if (res.code === 200) {
        // 如果勾选了"记住我"，则保存学号到localStorage
        if (loginForm.remember) {
          localStorage.setItem('studentNumber', loginForm.studentNumber)
        } else {
          localStorage.removeItem('studentNumber')
        }

        // 保存用户信息到store
        await userStore.setUserInfo(res.data)

        ElMessage.success('登录成功')
        router.push('/')
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录请求失败:', error)
      ElMessage.error('登录请求失败，请稍后再试')
    }
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    loading.value = false
  }
}

const goToForgetPassword = () => {
  router.push('/forget-password')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  background-image: linear-gradient(to right, #f5f7fa, #c3cfe2);
  flex-direction: column;
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 10px;
}

.login-header p {
  color: #606266;
  font-size: 16px;
}

.login-form {
  margin-bottom: 20px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  color: #606266;
}

.register-link a {
  margin-left: 5px;
  color: #409eff;
  text-decoration: none;
}

@media screen and (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px;
  }
}

.project-info {
  margin-top: 20px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>
